package org.tgcloud.group.service.app;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.TypeReference;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.tgcloud.group.core.*;
import org.tgcloud.group.core.ExportUtils.ExcelUtils;
import org.tgcloud.group.core.fileUtils.FileUtil;
import org.tgcloud.group.entity.MjNormalUser;
import org.tgcloud.group.entity.MjOrder;
import org.tgcloud.group.entity.MjOrderHotel;
import org.tgcloud.group.entity.MjOrderLocalLife;
import org.tgcloud.group.repository.*;
import org.tgcloud.group.web.controller.dto.file.HotelDownLoadDTO;
import org.tgcloud.group.web.controller.dto.file.LocalLifeDonLoadDTO;
import org.tgcloud.group.web.controller.dto.order.GoodListDTO;
import org.tgcloud.group.web.controller.dto.file.UserType1DTO;
import org.tgcloud.group.web.controller.dto.file.UserType2DTO;
import org.tgcloud.group.web.controller.req.file.FileOrderIdReq;

import java.io.File;
import java.net.URL;
import java.util.*;

/**
 * @author: zhy
 * @create: 2023-08-25 11:07
 * @description:
 */
@Service
public class FileService {

    @Autowired
    private MjNormalUserMapper normalUserMapper;

    @Autowired
    private MjGoodSkuMapper goodSkuMapper;

    @Autowired
    private MjOrderMapper orderMapper;

    @Autowired
    private MjOrderLocalLifeMapper mjOrderLocalLifeMapper;

    @Autowired
    private MjOrderHotelMapper mjOrderHotelMapper;

    @Autowired
    private HttpClientUtil clientUtil;

    public APPResultMessage doDownloadFile(int userId, short userType, FileOrderIdReq req) throws Exception{
        MjOrder mjOrder = orderMapper.selectByPrimaryKey(req.getOrderId());
        String fileTitleName = mjOrder.getOrderKey();
        //TODO: 分辨文件是xls还是xlsx，预览和分享表单报错
        String path = ExcelUtils.doViewFilePath(GlobalStatic.viewFilePath) + File.separator + fileTitleName + ".xlsx";
        if(StringUtil.isNotBlank(path)){
            String s = clientUtil.doGet(path, null);
            if (s.contains("500 Internal Server Error")){
                path = ExcelUtils.doViewFilePath(GlobalStatic.viewFilePath) + File.separator + fileTitleName + ".xls";
            }
        }
        String pathUrls = mjOrder.getPathUrls();
        if (StringUtil.isBlank(pathUrls)){
            mjOrder.setPathUrls(path);
            orderMapper.updateByPrimaryKeySelective(mjOrder);
        }

        MjNormalUser user = normalUserMapper.selectByPrimaryKey(userId);
        String waterMarkName = user.getTelephone();
        //如果没有创建过文件，就保存到服务器
        if (mjOrder.getFileType() == 1){
            List<GoodListDTO> goodListDTOS = goodSkuMapper.selectListByOrderId(req.getOrderId());
            if (user.getUserType() == 1){
                List<UserType1DTO> list = new ArrayList<UserType1DTO>();
                for (GoodListDTO dto : goodListDTOS){
                    UserType1DTO userTypeDTO = new UserType1DTO();
                    userTypeDTO.setGoodName(dto.getGoodName());
                    userTypeDTO.setGoodSkuName(dto.getGoodSku());
                    userTypeDTO.setExpirationDate(dto.getGoodExpirationDate());
                    userTypeDTO.setWarrantyDate(dto.getGoodWarrantyDate());
                    userTypeDTO.setGoodNum(dto.getGoodSkuNum());
                    userTypeDTO.setGoodPrice(dto.getGoodSkuPrice());
                    userTypeDTO.setGoodOnlineLink(dto.getGoodOnlineLink());
                    if (StringUtil.isNotBlank(dto.getGoodSkuPic())){
                        List<URL> imageUrlList = new ArrayList<>();
                        imageUrlList.add(new URL(dto.getGoodSkuPic()));
                        userTypeDTO.setGoodPic(imageUrlList);
                    }
                    list.add(userTypeDTO);
                }
                FileUtil.doWaterMarkReader(list, waterMarkName, fileTitleName, UserType1DTO.class);
            }else {
                List<UserType2DTO> list = new ArrayList<UserType2DTO>();
                for (GoodListDTO dto : goodListDTOS){
                    UserType2DTO userTypeDTO = new UserType2DTO();
                    userTypeDTO.setGoodName(dto.getGoodName());
                    userTypeDTO.setGoodSkuName(dto.getGoodSku());
                    userTypeDTO.setExpirationDate(dto.getGoodExpirationDate());
                    userTypeDTO.setWarrantyDate(dto.getGoodWarrantyDate());
                    userTypeDTO.setGoodNum(dto.getGoodSkuNum());
                    userTypeDTO.setGoodPrice(dto.getGoodSkuPrice());
                    userTypeDTO.setGoodOnlineLink(dto.getGoodOnlineLink());
                    if (StringUtil.isNotBlank(dto.getGoodSkuPic())){
                        List<URL> imageUrlList = new ArrayList<>();
                        imageUrlList.add(new URL(dto.getGoodSkuPic()));
                        userTypeDTO.setGoodPic(imageUrlList);
                    }
                    userTypeDTO.setGoodBoxNum(dto.getGoodBoxNum());
                    userTypeDTO.setGoodBoxSize(dto.getGoodBoxSize());
                    userTypeDTO.setGoodOneSize(dto.getGoodOneSize());
                    userTypeDTO.setShopFans(dto.getShopFans());
                    userTypeDTO.setGoodSaleNum(dto.getGoodSaleNum());
                    userTypeDTO.setFinalPrice(dto.getFinalPrice());
                    list.add(userTypeDTO);
                }
                FileUtil.doWaterMarkReader(list, waterMarkName, fileTitleName, UserType2DTO.class);
            }
        } else if (mjOrder.getFileType() == 2){
            List<MjOrderLocalLife> mjOrderLocalLifeList = mjOrderLocalLifeMapper.selectListByOrderId(req.getOrderId());
            List<LocalLifeDonLoadDTO> list = new ArrayList<LocalLifeDonLoadDTO>();
            for (MjOrderLocalLife storeDto : mjOrderLocalLifeList) {
                LocalLifeDonLoadDTO localLife = new LocalLifeDonLoadDTO();
                localLife.setChainStoreName(storeDto.getChainStoreName());
                localLife.setNum(storeDto.getNum());
                localLife.setFinalPrice(storeDto.getFinalPrice());
                localLife.setCategory(storeDto.getCategory());
                localLife.setAverageScore(storeDto.getAverageScore());
                localLife.setCouponForm(storeDto.getCouponForm());
                localLife.setDistributedCities(storeDto.getDistributedCities());
                localLife.setCouponForm(storeDto.getCouponForm());
                localLife.setPrice(storeDto.getPrice());
                localLife.setProductName(storeDto.getProductName());
                localLife.setStoreLinks(storeDto.getStoreLinks());
                localLife.setUseRights(storeDto.getUseRights());
                localLife.setVerificationProcess(storeDto.getVerificationProcess());
                localLife.setUsageRestrictions(storeDto.getUsageRestrictions());
                localLife.setValidityPeriod(storeDto.getValidityPeriod());
                localLife.setStoreNumber(storeDto.getStoreNumber());
                list.add(localLife);
            }
            FileUtil.doWaterMarkReader(list, waterMarkName, fileTitleName, LocalLifeDonLoadDTO.class);
        } else if (mjOrder.getFileType() == 3){
            List<MjOrderHotel> mjOrderHotelList = mjOrderHotelMapper.selectListByOrderId(req.getOrderId());
            List<HotelDownLoadDTO> list = new ArrayList<HotelDownLoadDTO>();
            for (MjOrderHotel hotelDto : mjOrderHotelList) {
                HotelDownLoadDTO mjOrderHotel = new HotelDownLoadDTO();
                mjOrderHotel.setBusyTime(hotelDto.getBusyTime());
                mjOrderHotel.setHotelAddress(hotelDto.getHotelAddress());
                mjOrderHotel.setHotelName(hotelDto.getHotelName());
                mjOrderHotel.setHotelType(hotelDto.getHotelType());
                mjOrderHotel.setNum(hotelDto.getNum());
                mjOrderHotel.setPrice(hotelDto.getPrice());
                mjOrderHotel.setUrl(hotelDto.getUrl());
                mjOrderHotel.setExpirationDate(hotelDto.getExpirationDate());
                mjOrderHotel.setIsHaveMorning(hotelDto.getIsHaveMorning());
                mjOrderHotel.setRealPrice(hotelDto.getRealPrice());
                if (StringUtil.isNotBlank(hotelDto.getHotelPic())){
                    List<URL> imageUrlList = new ArrayList<>();
                    imageUrlList.add(new URL(hotelDto.getHotelPic()));
                    mjOrderHotel.setHotelPic(imageUrlList);
                }
                list.add(mjOrderHotel);
            }
            FileUtil.doWaterMarkReader(list, waterMarkName, fileTitleName, HotelDownLoadDTO.class);
        }


        Map map = new HashMap();
        map.put("title", fileTitleName);
        map.put("path", path);
        APPResultMessage successMessage = APPResultMessage.getSuccessMessage();
        ResultMessage resultMessage = ResultMessage.builder().setData(map);
        successMessage.setResult(resultMessage);
        return successMessage;
    }
}
